package ls.jpa.chapterA.expressions;

import ls.jpa.chapterA.domain.Customer;
import ls.jpa.chapterA.domain.Customer_;
import org.springframework.data.jpa.domain.Specification;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.Calendar;
import java.util.Date;

/**
 * 另外一种实现方式
 * @author Barudisshu
 */
public class CustomerSpecifications {

    public static Specification<Customer> customerHasBirthday() {
        return new Specification<Customer>() {
            @Override
            public Predicate toPredicate(Root<Customer> customerRoot, CriteriaQuery<?> criteriaQuery, CriteriaBuilder
                    criteriaBuilder) {
                return criteriaBuilder.equal(customerRoot.get(Customer_.birthday),new Date());
            }
        };
    }

    public static Specification<Customer> isLongTermCustomer() {
        final Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.YEAR, -2);
        return new Specification<Customer>() {
            @Override
            public Predicate toPredicate(Root<Customer> customerRoot, CriteriaQuery<?> criteriaQuery, CriteriaBuilder
                    criteriaBuilder) {
                return criteriaBuilder.equal(customerRoot.get(Customer_.createdAt),calendar.getTime());
            }
        };
    }
}
